<!DOCTYPE html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <meta charset="utf-8"/>
    <title>peer</title>
</head>
<body onload="javascript:load();">
<h1>webRTC</h1>
<p>video</p>
<video id="localVideo" autoplay style="width: 200px;height: 200px;border: 1px red solid"></video>
<video id="remoteVideo" autoplay style="width: 200px;height: 200px;border: 1px red solid"></video>
<p></p>
<button type="button" onclick="javascript:getCamera();">getCamera</button>&nbsp;&nbsp;
<button type="button" onclick="javascript:createOfferAndSetLocal();">createOfferAndSetLocal</button>
<p>LocalDescription</p>
<input id="LocalDescription" type="text" style="width:400px;"></input>
<p>RemoteDescription</p>
<input id="RemoteDescription" type="text" style="width:400px;"></input>

<script type="text/javascript">

    var server;
    var constraints = {video: true, audio: true};
    var ice = {"iceServers": [{"url": "turn:47.104.137.175:3478", "username": "gpf", "credential": "root"}]};

    // 获取摄像头
    function getCamera() {
        navigator.getUserMedia(constraints, onGetCameraSuccess, onGetCameraError);
    }
    function onGetCameraSuccess(stream) {
        var localVideo = document.getElementById('localVideo');
        localVideo.srcObject = stream;
        var localStream = stream;

        localStream.getTracks().forEach(
            function (track) {
                server.addTrack(track, localStream);
            }
        );
    }
    function onGetCameraError(error) {
        console.log("navigator.getUserMedia error: ", error);
    }


    // 创建offer
    var offerOptions = {
        offerToReceiveAudio: 1,
        offerToReceiveVideo: 1
    };
    function createOfferAndSetLocal() {
        server.createOffer(offerOptions).then(
            onCreateOfferSuccess,
            onCreateOfferError
        );
    }
    function onCreateOfferSuccess(desc) {
        server.setLocalDescription(desc);
        var descString = JSON.stringify(desc);
        console.info("create offer :" + descString);
        document.getElementById("LocalDescription").value = descString;
        var sendMsg = {"key":"offer","value": desc};
        ws.send(JSON.stringify(sendMsg));
    }
    function onCreateOfferError(desc) {
        console.info(desc);
    }

    // 创建answer
    function setRemoteAndCreateAnswer(offer) {
        document.getElementById("RemoteDescription").value = JSON.stringify(offer);
        server.setRemoteDescription(offer);
        server.createAnswer().then(
            onCreateAnswerSuccess,
            onCreateAnswerError
        );
    }
    function onCreateAnswerSuccess(answer) {
        var sendMsg = {"key":"answer","value": answer};
        ws.send(JSON.stringify(sendMsg));
        setLocal(answer);
    }
    function onCreateAnswerError(desc) {
        console.info(desc);
    }

    function setLocal(offer) {
        server.setLocalDescription(offer);
        console.info("setLocal:" + JSON.stringify(offer));
        document.getElementById("LocalDescription").value = JSON.stringify(offer);
    }

    function setRemote(answer) {
        console.info("setRemote:" + JSON.stringify(answer));
        server.setRemoteDescription(answer);
        document.getElementById("RemoteDescription").value = JSON.stringify(answer);
    }


    // websock  通信部分
    var ws;
    if(location.protocol.indexOf("s" > 0)){
        ws = new WebSocket("wss://" + location.hostname + ":" + location.port +"/webRTCHandle");
    }else{
        ws = new WebSocket("ws://" + location.hostname + ":" + location.port +"/webRTCHandle");
    }

    ws.onopen = function () {
        var flag = {"key": "open", "value": "socket comein"};
        ws.send(JSON.stringify(flag));
    };
    ws.onmessage = function (evt) {
        var received_msg = evt.data;

        if (received_msg.indexOf("key") > 0) {
            var receive_msg_json = JSON.parse(received_msg);
            var key = receive_msg_json.key;
            var value = receive_msg_json.value;
            if (key == "candidate") {
                console.info("receive candidate :" + JSON.stringify(value));
                server.addIceCandidate(new RTCIceCandidate(value));
            } else if (key == "offer") {
                console.info("receive offer :" + JSON.stringify(value));
                setRemoteAndCreateAnswer(value);
            } else if (key == "answer") {
                console.info("receive answer :" + JSON.stringify(value));
                setRemote(value);
            } else if (key == "open") {
                console.info(value);
            }
        }
    };
    ws.onclose = function () {
        console.info("ws closed!");
    };


    function load() {
        navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
        if (navigator.getUserMedia) {
            server = new RTCPeerConnection(ice);
        } else {
            console.log("请使用chrome！");
            return;
        }

        server.onicecandidate = function (event) {
            if (event.candidate) {
                let candidate = event.candidate;
                console.info("generate candidate:" + JSON.stringify(candidate));
                var sendMsg = {"key":"candidate","value": candidate};
                ws.send(JSON.stringify(sendMsg));
            } else {
                // All ICE candidates have been sent
            }
        }

        server.onaddstream = function (event) {
            document.getElementById('remoteVideo').src = URL.createObjectURL(event.stream);
        };

        server.oniceconnectionstatechange = function (event) {
            console.info("ice status change :" + server.iceConnectionState);
        };
    }
</script>
</body>
</html>
